package com.dudu.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * http request请求辅助工具类
 * 
 * @author zx
 *
 */
public class RequestUtils {

	public static final String AMPERSAND_CHAR = "&";

	public static final String DEFAULT_CHARSET = "utf-8";

	private RequestUtils() {

	}

	/**
	 * 解析request中的参数，转换为querystring的格式
	 * 如果值为空，默认不返回
	 * @param request
	 * @param parser
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getParametersInQueryString(HttpServletRequest request, ParamterParser parser)
			throws UnsupportedEncodingException {
		return getParametersInQueryString(request, parser, false);
	}

	/**
	 * 解析request中的参数，转换为querystring的格式
	 * 
	 * @param request
	 * @param parser
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getParametersInQueryString(HttpServletRequest request, ParamterParser parser,
			boolean containsNull) throws UnsupportedEncodingException {
		Enumeration<String> en = request.getParameterNames();
		StringBuilder params = new StringBuilder(256);
		while (en.hasMoreElements()) {
			String name = en.nextElement();
			String value = request.getParameter(name);
			if (parser != null) {
				value = parser.parse(name, value);
			}
			if (containsNull || !StringUtils.isEmpty(value)) {
				params.append(name).append("=").append(value).append(AMPERSAND_CHAR);
			}
		}
		return params.substring(0, params.length() - 1);
	}

	public static String getEncodeParameter(String value) {
		if (StringUtils.isEmpty(value))
			return value;
		String ev = null;
		try {
			ev = URLEncoder.encode(value, DEFAULT_CHARSET);
		} catch (UnsupportedEncodingException e) {
			ev = value;
		}
		return ev;
	}

	public interface ParamterParser {

		String parse(String parameterName, String parameterValue);

	}

}
